import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:school_assistant/toast_utils.dart';
import 'package:sp_util/sp_util.dart';

import 'common_client.dart';
import 'common_colors.dart';
import 'data/user_extra_entity.dart';
import 'data/usr_extra_entity.dart';
import 'home_page.dart';
import 'login_page.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final GlobalKey _formKey = GlobalKey<FormState>();
  late String _email, _password, _rePassword, _name, _des;
  bool _isObscure = true;
  bool _isObscureRe = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey, // 设置globalKey，用于后面获取FormStat
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          children: [
            const SizedBox(height: kToolbarHeight), // 距离顶部一个工具栏的高度
            buildTitle(), // Login
            buildTitleLine(), // Login下面的下划线
            const SizedBox(height: 25),
            buildEmailTextField(), // 输入邮箱
            const SizedBox(height: 10),
            buildPasswordTextField(context), // 输入密码
            const SizedBox(height: 10),
            buildRePasswordTextField(context), // 确认密码
            const SizedBox(height: 10),
            buildNameTextField(), // 姓名
            const SizedBox(height: 15),
            buildDesTextField(), // 姓名简介
            const SizedBox(height: 60),
            buildLoginButton(context),
            const SizedBox(height: 40),
            buildLoginText(),
            const SizedBox(height: 40),
          ],
        ),
      ),
    );
  }

  Widget buildLoginText() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.only(top: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('已有账号?'),
            GestureDetector(
              child: const Text('点击登录', style: TextStyle(color: Colors.green)),
              onTap: () {
                Get.to(LoginPage());
              },
            )
          ],
        ),
      ),
    );
  }

  _register() async {
    try {
      var extraD = UsrExtraEntity();
      extraD.des = _des;
      var res = await CommonClient().register(
          _email, _password, _name, "暂无", "", 0, 1,
          extra: jsonEncode(extraD));
      if (res.status == true) {
        QmToast.toast("注册成功");
        SpUtil.putString("uid", res.data ?? '');
        SpUtil.putString("lastUsr", _email);
        SpUtil.putString("lastPwd", _password);
        Get.offAll(HomePage(), transition: Transition.zoom);
      } else {
        QmToast.toast("注册失败！");
      }
    } catch (e) {
      QmToast.toast("注册失败！");
      print(e);
    }
  }

  Widget buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45,
        width: 270,
        child: TextButton(
          style: TextButton.styleFrom(
            foregroundColor: CommonColor.colorMainGreen,
            backgroundColor: CommonColor.colorMainGreen,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),
                side: const BorderSide(
                  style: BorderStyle.none,
                )),
          ),
          onPressed: () {
            if ((_formKey.currentState as FormState).validate()) {
              (_formKey.currentState as FormState).save();
              _register();
            }
          },
          child: Text(
            '注册',
            style: TextStyle(color: CommonColor.color33, fontSize: 16),
          ),
        ),
      ),
    );
    return Align(
      child: SizedBox(
        height: 45,
        width: 270,
        child: ElevatedButton(
          style: ButtonStyle(
              // 设置圆角
              shape: MaterialStateProperty.all(const StadiumBorder(
                  side: BorderSide(style: BorderStyle.none)))),
          child:
              Text('注册', style: Theme.of(context).primaryTextTheme.headline5),
          onPressed: () {
            // 表单校验通过才会继续执行
            if ((_formKey.currentState as FormState).validate()) {
              (_formKey.currentState as FormState).save();
              //TODO 执行登录方法
              print('email: $_email, password: $_password');
            }
          },
        ),
      ),
    );
  }

  Widget buildForgetPasswordText(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Align(
        alignment: Alignment.centerRight,
        child: TextButton(
          onPressed: () {
            // Navigator.pop(context);
            print("忘记密码");
          },
          child: const Text("忘记密码？",
              style: TextStyle(fontSize: 14, color: Colors.grey)),
        ),
      ),
    );
  }

  Widget buildPasswordTextField(BuildContext context) {
    return TextFormField(
        obscureText: _isObscure,
        maxLength: 8,
        // 是否显示文字
        onSaved: (v) => _password = v!,
        onChanged: (v) => _password = v,
        validator: (v) {
          if (v!.isEmpty) {
            return '请输入密码';
          }
        },
        decoration: InputDecoration(
            labelText: "密码",
            counterText: '',
            suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _isObscure
                    ? Colors.grey
                    : Theme.of(context).iconTheme.color,
              ),
              onPressed: () {
                // 修改 state 内部变量, 且需要界面内容更新, 需要使用 setState()
                setState(() {
                  _isObscure = !_isObscure;
                });
              },
            )));
  }

  Widget buildRePasswordTextField(BuildContext context) {
    return TextFormField(
        maxLength: 8,
        obscureText: _isObscureRe,
        // 是否显示文字
        onSaved: (v) => _rePassword = v!,
        validator: (v) {
          if (v!.isEmpty) {
            return '请再次输入密码';
          }
          if (v != _password) {
            return '两次输入密码不一致';
          }
        },
        decoration: InputDecoration(
            counterText: '',
            labelText: "确认密码",
            suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _isObscureRe
                    ? Colors.grey
                    : Theme.of(context).iconTheme.color,
              ),
              onPressed: () {
                _isObscureRe = !_isObscureRe;
                // 修改 state 内部变量, 且需要界面内容更新, 需要使用 setState()
                setState(() {});
              },
            )));
  }

  Widget buildEmailTextField() {
    return TextFormField(
      decoration: const InputDecoration(labelText: '邮箱地址'),
      validator: (v) {
        var emailReg = RegExp(
            r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
        if (!emailReg.hasMatch(v!)) {
          return '请输入正确的邮箱地址';
        }
      },
      onSaved: (v) => _email = v!,
    );
  }

  Widget buildNameTextField() {
    return TextFormField(
      decoration: const InputDecoration(labelText: '姓名'),
      validator: (v) {
        if (v!.isEmpty) {
          return '请输入姓名';
        }
        if (v.toString().length > 4) {
          return '姓名不符合规范';
        }
      },
      onSaved: (v) => _name = v!,
    );
  }

  Widget buildDesTextField() {
    return TextFormField(
      maxLines: 2,
      textAlign: TextAlign.start,
      decoration:
          const InputDecoration(labelText: '简介', labelStyle: TextStyle()),
      onSaved: (v) => _des = v!,
    );
  }

  Widget buildTitleLine() {
    return Padding(
        padding: const EdgeInsets.only(left: 1, top: 4.0),
        child: Align(
          alignment: Alignment.bottomLeft,
          child: Container(
            color: Colors.black,
            width: 100,
            height: 2,
          ),
        ));
  }

  Widget buildTitle() {
    return const Padding(
        padding: EdgeInsets.only(top: 20, left: 0, right: 0),
        child: Text(
          '用户注册',
          style: TextStyle(fontSize: 26),
        ));
  }
}
